package db

import (
	"context"

	"github.com/neo4j/neo4j-go-driver/v5/neo4j"
)

type Role struct {
	_Node_ `mapstructure:",squash"`
	Name   string `mapstructure:"name" json:"name"`
}

const createRole = `
// name CreateRole :one
CREATE (r:Role {name: $name})
RETURN r
`

type CreateRoleParam struct {
	Name string `map:"name"` // string
}

func (dao *DAO) CreateRole(ctx context.Context, arg CreateRoleParam) (Role, error) {
	var i Role
	argMap, err := NewParamConverter(&arg).AsMap()
	if err != nil {
		return i, err
	}
	_, err = dao.db.ExecTx(ctx, func(tx NeoTransaction) error {
		result, err := tx.Run(ctx, createRole, argMap)
		if err != nil {
			return err
		}
		err = NewNodeLoader(&i).LoadT(ctx, result, "r")
		if err != nil {
			return err
		}
		dao.db.slog.Infof("i=>%+v", i)
		return nil
	}, neo4j.ExecuteQueryWithDatabase(dao.dbName))

	return i, err
}

const getRoleByID = `
MATCH (r:Role)
WHERE elementId(r) = $uuid
RETURN r
`

func (dao *DAO) GetRoleByID(ctx context.Context, uuid string) (Role, error) {
	var i Role
	argMap, err := NewParamConverter(&uuid).AsMap()
	if err != nil {
		return i, err
	}
	result, err := dao.db.ExecuteQuery(ctx, getRoleByID, argMap, neo4j.ExecuteQueryWithDatabase(dao.dbName))
	if err != nil {
		return i, err
	}
	err = NewNodeLoader(&i).LoadE(ctx, result, "r")
	if err != nil {
		return i, err
	}
	return i, err
}
